package com.jingyi.web.controller.wechat;

import com.alibaba.fastjson2.JSONObject;
import com.jingyi.common.annotation.Anonymous;
import com.jingyi.common.config.WxAuthConfig;
import com.jingyi.common.core.domain.entity.WxUser;
import com.jingyi.common.utils.http.HttpUtils;
import com.jingyi.framework.util.CodeGenerator;
import com.jingyi.system.service.IWxUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 微信公众号网页授权登录相关接口
 *
 * @author jingyi
 */
@Controller
@RequestMapping("/wxchat/auth")
public class WxAuthController {

    private static final Logger log = LoggerFactory.getLogger(WxAuthController.class);

    @Autowired
    private WxAuthConfig wxAuthConfig;

    @Autowired
    private CodeGenerator codeGenerator;

    @Autowired
    private IWxUserService wxUserService;


    /**
     * 用户登录url
     *
     * appId: 微信授权第三方应用
     * @return url
     */
    @GetMapping("/wxlogin")
    @Anonymous
    public String wxlogin(){
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ wxAuthConfig.getAppId() +
                "&redirect_uri=" + wxAuthConfig.getCallback() +
                "&response_type=code" +
                "&scope=snsapi_userinfo"+
                "&state=123#wechat_redirect";
        return "redirect:" + url;
    }


    /**
     * 用户登录url
     *
     * @return url
     */
    @GetMapping("/greenLogin")
    @Anonymous
    public String query(){
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ wxAuthConfig.getAppId() +
                "&redirect_uri=" + wxAuthConfig.getQueryCallback() +
                "&response_type=code" +
                "&scope=snsapi_userinfo"+
                "&state=123#wechat_redirect";
        return "redirect:" + url;
    }

    /**
     * 微信oauth远程调用方法，发送code
     *
     * @return userInfo
     */
    @GetMapping("/wxcallback")
    @Anonymous
    public String wxcallback(String code){
        //获取token
        String accessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+wxAuthConfig.getAppId()+
                "&secret="+ wxAuthConfig.getAppSecret() +
                "&code="+ code +
                "&grant_type=authorization_code";
        JSONObject accessTokenJson = HttpUtils.senGet(accessUrl);
        String access_token = accessTokenJson.getString("access_token");

        //获取用户信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?"+
                "access_token=" + access_token +
                "&openid=" + wxAuthConfig.getAppId() +
                "&lang=zh_CN";

        JSONObject userInfoJson = HttpUtils.senGet(userInfoUrl);

        //用户注册
        WxUser wxUser = new WxUser(userInfoJson.getString("nickname"),userInfoJson.getString("openid"),userInfoJson.getString("headimgurl"),codeGenerator.nextCode("wx_user"));
        if(StringUtils.isNotEmpty(wxUser.getOpenId())){
            wxUser = wxUserService.insertOrUpdateByOpenId(wxUser);
        }

        String redirectUrl = wxAuthConfig.getRedirectUrl() +"?"+
                "openId="+ userInfoJson.getString("openid");
        log.info("redirect to:"+redirectUrl);
        return "redirect:"+redirectUrl;
    }

    /**
     * 用户登录回调函数
     *
     * @return userInfo
     */
    @GetMapping("/queryCallback")
    @Anonymous
    public String queryCallback(String code){
        //获取token
        String accessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+wxAuthConfig.getAppId()+
                "&secret="+ wxAuthConfig.getAppSecret() +
                "&code="+ code +
                "&grant_type=authorization_code";
        JSONObject accessTokenJson = HttpUtils.senGet(accessUrl);
        String access_token = accessTokenJson.getString("access_token");

        //获取用户信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?"+
                "access_token=" + access_token +
                "&openid=" + wxAuthConfig.getAppId() +
                "&lang=zh_CN";

        JSONObject userInfoJson = HttpUtils.senGet(userInfoUrl);

        //用户注册
        WxUser wxUser = new WxUser(userInfoJson.getString("nickname"),userInfoJson.getString("openid"),userInfoJson.getString("headimgurl"),codeGenerator.nextCode("wx_user"));
        if(StringUtils.isNotEmpty(wxUser.getOpenId())){
            wxUser = wxUserService.insertOrUpdateByOpenId(wxUser);
        }

        String redirectUrl = wxAuthConfig.getQueryRedirectUrl() +"?"+
                "openId="+ userInfoJson.getString("openid");
        log.info("redirect to:"+redirectUrl);
        return "redirect:"+redirectUrl;
    }


}
